function ode2vfgen(srcfilename, destinationFile)
% code conversion from ODE file for XPP to a .vcml file for Virtual Cell


fileExtension='vf';

% input checking
if nargin==0 || isempty(srcfilename)
    [name,path]=uigetfile('.ode','Select an ODE file');
    srcfilename=fullfile(path,name);
end
    
% Extract info from the ODE file
xppdata=parseODEfile(srcfilename);

%Build the destination filename
if ~exist('destinationFile','var')||isempty(destinationFile)
    destinationFile=xppdata.name;
end
destinationFile=[destinationFile '.' fileExtension];
%end build destination filename

output_file=BuildOutputFile(xppdata);
lineCount=length(output_file);

%delete a previous version - silently destroys any previous version!
fullPath=[pwd filesep destinationFile];
if exist(fullPath,'file')==2
    delete(fullPath)
end

% write to file
fidw=fopen(fullPath,'w','n','UTF-8');

if fidw > -1
    for line=1:lineCount
        fprintf(fidw, '%s\n', output_file{line});
    end
    status=fclose(fidw);
else
    fprintf(' Problem opening file %s for writing. Cannot continue\n',fullPath);
    return
end


%check to make sure file is written
ready=false;
while ~ready
    status=exist(fullPath,'file');
    if status
        ready=true;
    end
end

success = true;
return

end

function output_file=BuildOutputFile(xppdata)

% build the output as a cell array containing each line.
par=xppdata.par;
num=xppdata.num;
var=xppdata.var;
fixed=xppdata.fixed;
func=xppdata.func;
aux=xppdata.aux;

if xppdata.nFunc>0
    disp([func(1).name '(' func(1).full_arglist ')='  func(1).formula])
    error('"name(var1,var2,...)=formula" function notation not yet supported');
end


output_file={};
output_file{end+1}='<?xml version="1.0" ?>';
output_file{end+1}='<!--This file was generated by ode2vfgen-->';


%Begin VectorField block
output_file{end+1}=['<VectorField Name="' xppdata.name '">'];

%constants
for i=1:xppdata.nNum
    output_file{end+1}=['<Constant Name="' num(i).name '" Value="' num2str(num(i).value) '" />'];
end

%parameters
for i=1:xppdata.nPar
    output_file{end+1}=['<Parameter Name="' par(i).name '" DefaultValue="' num2str(par(i).value) '" />'];
end

%Expressions
for i=1:xppdata.nFixed
    output_file{end+1}=['<Expression  Name="' fixed(i).name '" Formula="' fixed(i).formula '"/>'];
end

%State Variables
for i=1:xppdata.nVar
    output_file{end+1}=['<StateVariable   Name="' var(i).name '" ' ...
                                         'Formula="' var(i).formula '" '...
                                         'DefaultInitialCondition="' num2str(var(i).value) '"/>'];
end

%User Functions
for i=1:xppdata.nAux
    output_file{end+1}=['<Function  Name="aux_' aux(i).name '" Formula="' aux(i).formula '"/>'];
end

output_file{end+1}='</VectorField>';
%End VectorField Block
end